package com.wx.spider.java.service.impl;

import com.wx.spider.common.model.CommonResponse;
import com.wx.spider.common.model.mq.GetListMessage;
import com.wx.spider.common.pojo.db.MqErrorLog;
import com.wx.spider.common.pojo.db.WxBizNews;
import com.wx.spider.common.util.JsoupUtil;
import com.wx.spider.common.util.StringUtil;
import com.wx.spider.java.feign.SqlWsClient;
import com.wx.spider.java.service.PMToJavaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author:feng
 * @create:2021-04-26 11:45
 */
@Service
public class PMToJavaServiceImpl implements PMToJavaService {
    @Autowired
    private SqlWsClient sqlWsClient;

    @Override
    public void saveMqErrorLog(MqErrorLog mqErrorLog) {
        sqlWsClient.saveMqErrorLog(mqErrorLog);
    }

    @Override
    public Boolean getContent(GetListMessage getListMessage) {

        try {
            if(getListMessage == null || getListMessage.getNewsId() == null){
                return false;
            }

            WxBizNews wxBizNews = sqlWsClient.getWxBizNewsById(getListMessage.getNewsId()).getData();
            if (wxBizNews == null || wxBizNews.getContentUrl() == null){
                return false;
            }
            String link = wxBizNews.getContentUrl();
            Map<String, String> map = null;
            if("0".equals(wxBizNews.getItemShowType())){
                map = JsoupUtil.getWxContentAndMd(link);
            }else{
                map = JsoupUtil.getWxContentAndMdImg(link);
            }
            if(map == null || map.get("content") == null){
                return false;
            }

            wxBizNews.setContent(StringUtil.removeEmj(map.get("content")));
            if (map.get("media") != null && (wxBizNews.getMedia() == null || !wxBizNews.getMedia().equals(map.get("media")))){
                wxBizNews.setMedia(map.get("media"));
            }

            wxBizNews.setIsContent(1);

            CommonResponse<WxBizNews> wxBizNewsCommonResponse = sqlWsClient.updateWxBizNews(wxBizNews);
            if("0000".equals(wxBizNewsCommonResponse.getCode())){
                System.out.println("Success update news!");
            }else{
                System.out.println("Fail update news!");
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
